package P6.T05;

import javax.swing.*;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.text.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class JMyFrame extends JFrame {
    public JMyFrame() {
        this.setTitle("My Frame");
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.setSize(500, 500);
        this.setLocationRelativeTo(null);
        JTextPane tp=new JTextPane();
        JButton btn=new JButton("居中");
        add(tp,BorderLayout.CENTER);
        add(btn,BorderLayout.SOUTH);
        ((AbstractDocument)tp.getDocument()).setDocumentFilter(new DocumentFilter(){
            //documentFilter的相关方法会在真正删除、插入之前被调用，且允许用户终止相应的动作
            @Override
            public void remove(FilterBypass fb, int offset, int length) throws BadLocationException {
                String str=fb.getDocument().getText(offset,length);
                super.remove(fb, offset, length);
                JMyFrame.this.setTitle("删除了%s".formatted(str));
            }
        });
        btn.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                StyledDocument doc=tp.getStyledDocument();
                SimpleAttributeSet attr=new SimpleAttributeSet();
                StyleConstants.setAlignment(attr, StyleConstants.ALIGN_CENTER);
                tp.setParagraphAttributes(attr,false);
            }
        });

        tp.getDocument().addDocumentListener(new DocumentListener() {
            @Override
            public void insertUpdate(DocumentEvent e) {
                try {
                    JMyFrame.this.setTitle("inserted "+e.getDocument().getText(e.getOffset(),e.getLength()));
                } catch (BadLocationException ex) {
                    throw new RuntimeException(ex);
                }
            }

            @Override
            public void removeUpdate(DocumentEvent e) {
                //该事件仅通知删除了内容，并不负责通知被删除的数据是什么
                JMyFrame.this.setTitle("deleted ");
            }

            @Override
            public void changedUpdate(DocumentEvent e) {
                //纯文本编辑本事件不会被触发，富文本编辑修改属性时本事件触发
                JMyFrame.this.setTitle("changed");
            }
        });
        this.setVisible(true);
    }
}
